package com.ljz.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.ljz.dao.EmpDao;
import com.ljz.utils.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


@WebServlet("/delEmps")
public class DelEmpServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSession();
        Gson gson = new Gson();
        String ids = req.getParameter("list");
        // 读取请求体中的 JSON 数据
        JsonObject jsonObject = gson.fromJson(ids, JsonObject.class);
        List<Integer> list = gson.fromJson(jsonObject.get("list"), new TypeToken<List<Integer>>(){}.getType());
        System.out.println(list);
        EmpDao empDao = sqlSession.getMapper(EmpDao.class);
        int num = empDao.delEmpById(list);
        sqlSession.commit();
        sqlSession.close();
        PrintWriter out = resp.getWriter();
        resp.setContentType("text/html;charset=utf-8");
        if(num > 0) {
            out.print("true");
        } else {
            out.print("false");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
